package com.loves.aouth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.loves.aouth.service.MailService;
import com.loves.aouth.vo.MailVo;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

@Service
@RabbitListener(queues = "mail.queue")
public class MailServiceImpl implements MailService {

    private Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendMail(MailVo mailVo) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(from);
        helper.setTo(mailVo.getTo());
        helper.setSubject(mailVo.getSubject());
        helper.setText(mailVo.getText());
        try {
            mailSender.send(mimeMessage);
            logger.info("邮件发送成功");
            return true;
        } catch (MailException e) {
            logger.error("邮件发送失败, to: {}, title: {}", mailVo.getTo(), mailVo.getSubject(), e);
            return false;
        }
    }

    @RabbitListener(bindings = @QueueBinding(
       value = @Queue(value = "mail.queue", durable="true"),
       exchange = @Exchange(value = "mail.exchange", durable="true", type= "direct", ignoreDeclarationExceptions = "true"),
       key = "mail.routing.key")
    )
    @RabbitHandler
    public void consume(Message message, Channel channel) throws Exception {
        Map<String, Object> map = JSON.parseObject(new String(message.getBody()));
        String userName = (String) map.get("username");
        String usermail = (String)map.get("usermail");
        MessageProperties properties = message.getMessageProperties();
        long tag = properties.getDeliveryTag();
        MailVo mailVo = new MailVo();
        mailVo.setText("欢迎"+userName+"先生/小姐入职！");
        mailVo.setSubject("入职通知");
        mailVo.setTo(usermail);
        boolean success = sendMail(mailVo);
        if (success) {
            //msgLogService.updateStatus(msgId, Constant.MsgLogStatus.CONSUMED_SUCCESS);
            // 消费确认
            channel.basicAck(tag, false);
        } else {
            channel.basicNack(tag, false, true);
        }
    }
}
